const errorTypes = require('../constants/error-types');
const {getUserByPhone} = require('../service/user_service');
const md5password = require('../utils/password-handle');
const jwt=require("jsonwebtoken")
const verifyLogin = async (ctx, next) => {
    const { phone, password } = ctx.request.body;

    // 2.判断用户名或者密码不能空
    if (!phone || !password) {
      const error = new Error(errorTypes.PHONE_OR_PASSWORD_IS_REQUIRED);
      return ctx.app.emit('error', error, ctx);
    }
  
    // // 3.判断该用户是否存在
    const result = await getUserByPhone(phone);
    let servicePassword=result[0].dataValues.password
    if (result.length==0) {
      const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
      return ctx.app.emit('error', error, ctx);
    }
    if (md5password(password) !== servicePassword) {
        const error = new Error(errorTypes.PASSWORD_IS_INCORRENT);
        return ctx.app.emit('error', error, ctx);
    }
    ctx.user=result[0].dataValues
    await next();
}
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware~");
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization
  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, "token");
    ctx.user = result;
    await next();
  } catch (err) {
    const error = new Error(errorTypes.UNAUTHORIZATION);
    ctx.app.emit('error', error, ctx);
  }
}

module.exports = {
  verifyLogin,
  verifyAuth
}